const router = require('koa-router')()
const { models } = require('../../model')
const { convertToObjectId } = require('../../utils/db')
const UserController = require('../../controller/user')
const userController = new UserController()
const { process } = require('../../service/km')
const { toUpper } = require('lodash')

const KM_PUBLIC_ATTRS = {
  title: 1,
  draft: 1,
  content: 1,
  parentId: 1,
  createUserId: 1,
  updateUserId: 1,
  statistics: 1,
  type: 1,
  level: 1,
  seq: 1,
  status: 1,
  tags: 1,
  createWay: 1,
  contentForm: 1,
  fromCid: 1,
  kmSpaceId: 1
}

router.use(userController.userFilter())

// 列表
router.get('/list', async function (ctx) {
  const query = ctx.query
  const findQuery = {}
  findQuery.subject = query.subject
  findQuery.day = query.day
  let docs = []
  if (query.type === 'newrank') {
    docs = await models.KmNewrank
      .find(findQuery)
      .project({ title: 1, author: 1, url: 1, publishDay: 1, data: 1 })
      .limit(100)
      .toArray()
  } else {
    docs = await models.KmWoshipm
      .find(findQuery)
      .project({ cid: 1, title: 1, author: 1, href: 1, date: 1, data: 1 })
      .limit(100)
      .toArray()
  }

  // docs.forEach(e => {
  //     e._id = e._id.toString()
  // });
  ctx.wrapper.succ(docs)
})

// 列表
router.get('/menu', async function (ctx) {
  const query = ctx.query
  const findQuery = {}
  // 没有_user（没有登录）或_user角色不是管理员，看6
  if (ctx._user === undefined || ctx._user.role !== 0 || parseInt(query.status) === 6) {
    findQuery.status = 6
  } else {
    //
  }
  const docs = await models.Article
    .find(findQuery)
    .project({
      title: 1,
      parentId: 1,
      type: 1,
      level: 1,
      seq: 1,
      status: 1
    })
    .toArray()
  docs.forEach(doc => {
    doc._id = doc._id.toString()
    doc.seq ? doc.seq = parseInt(doc.seq) : doc.seq = -1
    if (doc.title === '' || doc.title === undefined) doc.title = '未命名文档'
    if (doc.status === 8) {
      doc.title = '已下线·' + doc.title
    } else if (doc.status === 1) {
      doc.title = '未发布·' + doc.title
    }
  })
  // query.sort
  // if (query.sorts === undefined || query.sorts === '') {
  //     query.sorts = {seq: 1}
  // } else {
  //     query.sorts = JSON.parse(query.sorts)
  // }
  docs.sort(function (a, b) { return a.seq - b.seq })

  // 转为树结构
  const array2Tree = (data, pid, level, parentPrefix) => {
    level++
    let showSeq = 1
    const res = []
    data.forEach(item => {
      if (item.parentId === pid) {
        item.level = level
        item.showSeq = showSeq++
        if (parentPrefix === '') {
          item.prefix = item.seq
        } else {
          item.prefix = parentPrefix + '.' + item.seq
        }
        // item.title = item.prefix + ' ' + item.title
        // item.title = item.showSeq + ' ' + item.title
        const itemChildren = array2Tree(data, item._id.toString(), level, item.prefix)
        item.children = itemChildren
        // q-menu不允许有相同的id，故生成新id，因为1个标签会有多个父标签
        // item.menuId = ++i
        res.push(item)
      }
    })
    return res
  }
  const docsTree = array2Tree(docs, '', 0, '')
  // 对于Topic下标签的不返回
  // docsTree = docsTree.filter(e => e.name !== 'Topic')
  ctx.wrapper.succ(docsTree)
})

// 文章内容
router.get('/article', async function (ctx) {
  const query = ctx.query
  const findQuery = {}

  if (query.id) {
    findQuery._id = convertToObjectId(query.id)
  } else {
    findQuery.isHomepage = 1
  }
  // query.sort
  if (ctx._user === undefined || ctx._user.role !== 0) findQuery.status = 6
  const doc = await models.Article
    .find(findQuery)
    .project(KM_PUBLIC_ATTRS)
    .limit(1)
    .toArray()

  if (toUpper(ctx.method) === 'GET' && doc) process(doc[0]._id)

  // 获取其各级父级id
  doc[0].parents = await getParents(doc[0].parentId)

  ctx.wrapper.succ(doc[0])
})

async function getParents (pid) {
  let parents = []
  if (pid === undefined || pid === '') return parents
  let doc = await models.Article
    .find({ _id: convertToObjectId(pid) })
    .project({ title: 1, parentId: 1 })
    .limit(1)
    .toArray()
  if (doc) {
    doc = doc[0]
    parents.push(doc)
    if (doc.parentId !== '') {
      // 若有父级，合并其父级
      parents = parents.concat(await getParents(doc.parentId))
    }
  }
  return parents
}

router.post('/create', async function (ctx) {
  // let user = ctx._user || ctx._tUser;
  if (ctx._user.role !== 0) return ctx.wrapper.console.error('PERMISSION_ERROR', '无权限')
  const doc = {
    createUserId: ctx._user._id,
    status: 1,
    statistics: { shows: 0, reads: 0, likes: 0, collects: 0, shares: 0 },
    parentId: ctx.request.body.parentId
  }
  const ret = await models.Article.insertOne(doc)
  return ctx.wrapper.succ({ _id: ret.insertedId })
})

router.post('/update', async function (ctx) {
  if (ctx._user.role !== 0) return ctx.wrapper.console.error('PERMISSION_ERROR', '无权限')
  const doc = ctx.request.body
  const _id = doc._id
  delete doc._id
  doc.updateUserId = ctx._user._id
  delete doc.user
  const ret = await models.Article.updateOne({
    _id: convertToObjectId(_id)
  }, {
    $set: doc
  }, { multi: false })
  return ctx.wrapper.succ(ret)
})

// 标签 - 获取所有 1/2/3 级标签
router.get('/tags', async function (ctx) {
  const tags = await models.Article.find({}).project({
    tags: 1
  }).sort({}).toArray()

  // 将 parentTags 数组解开来
  const set = new Set()
  tags.forEach(e => {
    if (e.tags && e.tags > 0) set.add(...e.tags)
  })

  ctx.wrapper.succ(set)
})

module.exports = router
